package com.admin.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.httpclient.HttpMethod;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFDateUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.StrKit;

/**
 * 通用方法
 * 
 * @author caohuayang 2015年5月22日
 */
public class UtilTools {
	private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	
	// 获取当前访问url
	public static String getUrl(HttpServletRequest request) {
		StringBuffer requestUrl = request.getRequestURL();
		String queryString = request.getQueryString();
		if (StrKit.notBlank(queryString)) {
			return requestUrl + "?" + queryString;
		}
		return requestUrl.toString();
	}
	
	// 转码
	public static String toUtf8(String str){
		try {
			if(null != str){
				String returnStr = new String(str.getBytes("ISO-8859-1"), "utf-8");
				return returnStr;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 判断str是否为空
	 * @param str
	 * @return
	 */
	public static boolean isNotNull(Object str){
		if(null != str && !str.equals("") && !str.equals("null")){
			return true; 
		}
		return false;
	}
	
	/**
	 * 将数组转换为字符串
	 * @param str
	 * @return
	 */
	public static String getStr(Object[] str){
		StringBuffer sb = new StringBuffer();
		for (Object string : str) {
			sb.append(string+",");
		}
		if(null != sb && sb.length() > 0){
			return sb.substring(0,sb.length()-1);
		}
		return null;
	}
	
	/**
	 * JSON对象
	 * 
	 * @param errorCode
	 * @param result
	 * @return
	 */
	public static JSONObject toJson(String errorCode, Object result) {
		JSONObject obj = new JSONObject();
		obj.put("CODE", errorCode);
		obj.put("RESULT", result);
		return obj;
	}

	/**
	 * 按开发要求把返回的JSON重新包装一层
	 * @param code 最外层的code
	 * @param obj 要包装的对象
	 * @return
	 */
	public static String warp(String code, Object obj) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("CODE", code);
		map.put("RESULT", obj);
		return JSON.toJSONString(map).toString();
	}
	
	/**
	 * 检测字符串是否不为空(null,"","null")
	 * 
	 * @param s
	 * @return 不为空则返回true，否则返回false
	 */
	public static boolean notEmpty(Object s) {
		return s != null && !"".equals(s) && !"null".equals(s);
	}

	/**
	 * 检测字符串是否为空(null,"","null")
	 * 
	 * @param s
	 * @return 为空则返回true，不否则返回false
	 */
	public static boolean isEmpty(Object s) {
		return s == null || "".equals(s) || "null".equals(s);
	}

	/**
	 * 检测集合是否为空(null,>0)
	 * 
	 * @param s
	 * @return 为空则返回false，否则返回true
	 */
	@SuppressWarnings({ "null", "rawtypes" })
	public static boolean notEmpty(List s) {
		return s != null || !"".equals(s) || !"null".equals(s) || s.size() > 0;
	}

	/**
	 * 倒序排列
	 * 
	 * @param returnList
	 * @param changeList
	 */
	public static void reverseOrderObj(LinkedList<Object> returnList,
			LinkedList<Object> changeList) {
		Object i = changeList.poll();
		if (changeList.size() == 0) {
			returnList.offer(i);
		} else {
			reverseOrderObj(returnList, changeList);
			returnList.offer(i);
		}
	}

	/**
	 * 获取返回内容
	 * 
	 * @param method
	 * @return
	 * @throws IOException
	 */
	public static String getContent(HttpMethod method) throws Exception {
		BufferedReader br = new BufferedReader(new InputStreamReader(
				method.getResponseBodyAsStream()));
		String line = null;
		StringBuffer sb = new StringBuffer();
		while ((line = br.readLine()) != null) {
			sb.append(line).append(System.getProperty("line.separator"));
		}
		br.close();

		return sb.toString();
	}

	/**
	 * 获取调用的方法名
	 * @param methodName
	 * @return
	 */
	public static String getMethodName(String[] methodNames){
		int length = methodNames.length;
		String methodName = "/" + methodNames[length - 2] + "/" + methodNames[length - 1];
		return methodName;
	}
	
	public static String getAddress(String address){
		String desenStr = address.replaceAll("[0-9]", "*");
		return desenStr;
	}
	
	 public static boolean isNumeric(String str) {  
	        for (int i = str.length(); --i >= 0;) {  
	            if (!Character.isDigit(str.charAt(i))) {  
	                return false;  
	            }  
	        }  
	        return true;  
	    }  
	
	 public static String parseTime(String originalTime) throws Exception{
		 String formateDate = new SimpleDateFormat("yyyy-MM-dd")
			.format(new SimpleDateFormat("MM/dd/yyyy hh:mm:ss")
					.parse(originalTime));
		 return formateDate;
	 }
	 
	 public static String parseUSTime(String USTime) throws Exception{
		 String formateDate = new SimpleDateFormat("yyyy-MM-dd")
			.format(new SimpleDateFormat("MMM d, yy",Locale.US)
					.parse(USTime));
		 return formateDate;
	 }
	 
	 /**
	 * 获取单元格中的值
	 * @param cell
	 * @return
	 */
	public static String getCellValue(HSSFCell cell) {
		String val = null;
		if(null != cell){
			int cellType = cell.getCellType();
			switch(cellType){
			case HSSFCell.CELL_TYPE_BLANK:
				break;
			case HSSFCell.CELL_TYPE_FORMULA:
				if(HSSFDateUtil.isCellDateFormatted(cell)){
					val = UtilTools.formatDate(cell.getDateCellValue(),"yyyy.M.d").trim();
				}else{
					val =cell.getCellFormula().trim();
				}
				break;
			case HSSFCell.CELL_TYPE_BOOLEAN:
				val = String.valueOf(cell.getBooleanCellValue());
				break;
			case HSSFCell.CELL_TYPE_NUMERIC:
				if(HSSFDateUtil.isCellDateFormatted(cell)){
					val = UtilTools.formatDate(cell.getDateCellValue(),"yyyy.M.d").trim();
				}else{
					BigDecimal bigDecimal = new BigDecimal(cell.getNumericCellValue());
					val = bigDecimal.toPlainString();
				}
				break;
			case HSSFCell.CELL_TYPE_STRING:
				val = cell.getStringCellValue().trim();
				break;
			default:
				break;
			}
		}
		if(val != null){
			val = val.trim();
		}
		return val;
	}
	
	public static String formatDate(Date d,String pattern){
		if(d == null){
			return "";
		}
		sdf.applyPattern(pattern);
		return sdf.format(d);
	}

	 
	public static void main(String[] args) throws Exception {
		String date1 = "Oct 31, 2005";
		SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat sdf = new SimpleDateFormat("MMM d, yy",Locale.US);
		System.out.println(sdf2.format(sdf.parse(date1)));
	}
}
